<!-- LoginByPhone.vue -->
<template>
    <div class="login-container">
        <div class="login-form">
            <h2>短信验证码登录</h2>
            <van-form @submit="onSubmit">
                <!-- 手机号输入 -->
                <van-cell-group inset>
                    <van-field v-model="form.phone" name="phone" label="手机号" placeholder="请输入手机号"
                        :rules="[{ required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]" />
                </van-cell-group>

                <!-- 验证码输入 -->
                <van-cell-group inset class="code-group">
                    <van-field v-model="form.code" name="code" label="验证码" placeholder="请输入验证码"
                        :rules="[{ required: true, pattern: /^\d{6}$/, message: '请输入6位验证码' }]">
                        <template #button>
                            <van-button size="small" type="primary" :disabled="isCounting" @click="sendSmsCode">
                                {{ codeButtonText }}
                            </van-button>
                        </template>
                    </van-field>
                </van-cell-group>

                <!-- 登录按钮 -->
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        登录
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { showFailToast, showSuccessToast } from 'vant'
import { useRouter } from 'vue-router'
import { getUserByPhone, addUser } from '../api/user'

// 表单数据
const form = reactive({
    phone: '',
    code: ''
})

// 验证码按钮状态
const isCounting = ref(false)
const countdown = ref(60)
const codeButtonText = ref('发送验证码')

// 路由实例
const router = useRouter()

// 发送验证码
const sendSmsCode = () => {
    // 验证手机号
    if (!/^1[3-9]\d{9}$/.test(form.phone)) {
        showFailToast('请输入正确的手机号')
        return
    }

    // 模拟发送验证码请求
    // 实际项目中应该调用后端API
    console.log(`发送验证码到手机号: ${form.phone}`)

    // 开始倒计时
    startCountdown()
    showSuccessToast('验证码已发送')
}

// 验证码倒计时
const startCountdown = () => {
    isCounting.value = true
    countdown.value = 60
    codeButtonText.value = `${countdown.value}秒后重发`

    const timer = setInterval(() => {
        countdown.value--
        if (countdown.value > 0) {
            codeButtonText.value = `${countdown.value}秒后重发`
        } else {
            clearInterval(timer)
            isCounting.value = false
            codeButtonText.value = '发送验证码'
        }
    }, 1000)
}

// 登录提交
const onSubmit = (values: typeof form) => {
    console.log('登录表单提交:', values)
    // 实际项目中应该调用后端登录API
    loginByPhone().then(() => {
        // 登录成功
        showSuccessToast('登录成功')
        // 跳转到首页或其他页面
        router.push('/')
    })
    // 验证验证码正确性
    // showSuccessToast('登录成功')
    // 跳转到首页或其他页面
    //  router.push('/')
}

const addUserInfo = async () => {
    const params = {
        "id": Math.floor(Math.random() * 1000000),
        "username": form.phone,
        "password": form.phone,
        "mobile": form.phone,
        "status": 1,  // 默认启用状态
        "version": 0,
        "createdAt": "",
        "updatedAt": "",
        "enterpriseId": 0,
        "role": "普通用户"
    }
    const response: any = await addUser(params)
    if (response.code === 200) {

    } else {
        showFailToast(response.message)
    }
    return response
}

const loginByPhone = async () => {
    let user
    // 1.获取手机号用户
    const response: any = await getUserByPhone(form.phone).catch(error => {
        console.log(error)
        return null
    })
    if (response?.code == 200) {
        user = response?.data

    } else {
        // 创建用户
        const responseCreate: any = await addUserInfo()
        user = responseCreate?.data
    }
    // console.log("登录的用户信息", user)
    localStorage.setItem('user', JSON.stringify(user))


}
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
}

.login-form {
    width: 80vw;
    padding: 30px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);

    margin-bottom: 25vh;
}

.login-form h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
}

.code-group :deep(.van-field__button) {
    padding: 0;
}
</style>